import React, { useEffect, useRef } from 'react'

interface ICodeTextViewProps {
    index: number
    value: Array<string>
    onInput: (index: number, value: string) => void
    selectedIndex: number
}

export function CodeTextView(props: ICodeTextViewProps) {
    const input = useRef<any>()

    useEffect(() => {
        if (props.selectedIndex === props.index) {
            input.current.focus()
        }
    }, [props.selectedIndex])

    return (
        <label
            key={props.index}
            className={`code__input__field ${props.index === props.selectedIndex ? 'active' : ''}`}
            htmlFor={props.index.toString()}>
            <input
                ref={input}
                id={props.index.toString()}
                type="text"
                maxLength={1}
                value={props.value[props.index]}
                // disabled={props.index !== props.selectedIndex}
                onChange={txt => props.onInput(props.index, txt.target.value)}
                onKeyUp={txt => {
                    if (txt.keyCode === 8) props.onInput(props.index, '-1')
                }}
            />
        </label>
    )
}
